package com.qzuser.sendmessagebasic.server.queue;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qzuser.sendmessagebasic.common.exception.ToolException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

public class Queue {
    private String name;
    private Boolean durable = false;
    private Boolean exclusive = false;
    private Boolean autoDelete = false;

    private Map<String, Object> arguments = new HashMap<String, Object>();

    private List<ConsumerEntity> consumerList = new ArrayList<>();
    private AtomicInteger consumerSeq = new AtomicInteger(0);
    public String getName() {
        return name;
    }

    public void setName(String queueName) {
        this.name = queueName;
    }

    public Boolean getDurable() {
        return durable;
    }

    public void setDurable(Boolean durable) {
        this.durable = durable;
    }

    public List<ConsumerEntity> getConsumerList() {
        return consumerList;
    }

    public void setConsumerList(List<ConsumerEntity> consumerList) {
        this.consumerList = consumerList;
    }

    public AtomicInteger getConsumerSeq() {
        return consumerSeq;
    }

    public void setConsumerSeq(AtomicInteger consumerSeq) {
        this.consumerSeq = consumerSeq;
    }

    public Boolean getExclusive() {
        return exclusive;
    }

    public void setExclusive(Boolean exclusive) {
        this.exclusive = exclusive;
    }

    public Boolean getAutoDelete() {
        return autoDelete;
    }

    public void setAutoDelete(Boolean autoDelete) {
        this.autoDelete = autoDelete;
    }

    public String getArguments() throws ToolException {
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.writeValueAsString(arguments);
        } catch (JsonProcessingException e) {
            throw new ToolException("[Queue] map对象序列化为json失败");
        }
    }

    public void setArguments(Map<String, Object> arguments) {
        this.arguments = arguments;
    }

    public void setArguments(String objectJson) throws ToolException {
        ObjectMapper mapper = new ObjectMapper();
        try {
            arguments = mapper.readValue(objectJson, new TypeReference<HashMap<String, Object>>() {});
        } catch (JsonProcessingException e) {
            throw new ToolException("[Queue] json序列化为map对象失败");
        }
    }

    public ConsumerEntity getConsumer() {
        if (consumerList.isEmpty()) {
            return null;
        }
        int seq = consumerSeq.get() % consumerList.size();
        consumerSeq.getAndIncrement();
        return consumerList.get(seq);
    }

    public void addConsumer(ConsumerEntity consumer) {
        consumerList.add(consumer);
    }
}
